package com.net.xpay.operator.interceptor;

import com.net.xpay.operator.secutiry.Operator;
import com.net.common.util.NetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Eric
 */
public class MvcAccessLogInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(MvcAccessLogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse rsp, Object handler) throws Exception {
        Operator user = Operator.getCurrentOperator();
        Long userId = user == null ? null : user.getOperatorId();
        String queryString = req.getQueryString() == null ? "" : ("?" + req.getQueryString());
        String ip = NetUtil.getRequestRealIp(req);

        MDC.put("user", ip + "-" + (userId == null ? "-" : userId));

        LOGGER.info("{} -- {} mvc access {}", req.getMethod(), userId, req.getRequestURI() + queryString);
        return super.preHandle(req, rsp, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse rsp, Object handler, Exception ex) {
        MDC.clear();
    }

}
